package com.mulanweb.api.module.controller.admin;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.utils.AseUtils;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.validator.annotation.ValidateForm;

import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class OrderController extends BaseController {

    @ValidateForm
    public void search() {
        SQLGenerateHelper helper = new SQLGenerateHelper("`order`", "create_time desc");
        Integer targetTypeId = getParaToInt("targetTypeId");
        Integer typeId = getParaToInt("typeId");
        helper.addEqualsCondition("type_id", typeId);
        helper.addEqualsCondition("status_id", getParaToInt("statusId"));
        helper.addEqualsCondition("order_number", getPara("orderNumber"));
        helper.addEqualsCondition("mobile_number", getPara("mobileNumber"));
        helper.addCondition("verify_time", ">=", getPara("startVerifyTime"));
        helper.addCondition("verify_time", "<=", getPara("endVerifyTime"));
        String nickname = getPara("wechatNickname");
        List<Long> userIds = new ArrayList<>();
        if (StrKit.notBlank(nickname)) {
            List<User> userList = User.dao.find("SELECT * FROM `user` WHERE wechat_nickname LIKE ?","%"+nickname+"%");
            for (User user : userList) {
                userIds.add(user.getId());
            }
        }
        String couponCode =  getPara("couponCode");
        Coupon coupon = Coupon.dao.findFirst("SELECT * FROM coupon WHERE coupon_code = ?" ,couponCode);
        Long couponId = 0L ;
        if(coupon !=null){
            couponId = coupon.getId();
        }
        if(couponCode != null){
            helper.addEqualsCondition("coupon_id",couponId);
        }
        helper.addInConditionToLong("user_id",userIds);
        Page<Order> page = Order.dao.paginate(getParaToInt("PageNumber"), getParaToInt("PageSize"), helper.getSqlSelect(), helper.getSqlExceptSelect(), helper.getQueryParas());
        if (targetTypeId != null) {
            List<Order> list = new ArrayList<>();
            if (typeId == 23) {
                for (Order oo : page.getList()) {
                    Ticket ticket = Ticket.dao.findById(oo.getTargetId());
                    if (ticket.getTypeId() == targetTypeId) list.add(oo);
                }
            } else if (typeId == 24) {
                for (Order oo : page.getList()) {
                    List<CharteredJoinType> targetTypes = CharteredJoinType.dao.find("SELECT * FROM chartered_join_type WHERE chartered_id=?", oo.getTargetId());
                    for (CharteredJoinType cjt : targetTypes) {
                        if (cjt.getTypeId() == targetTypeId) list.add(oo);
                    }
                }
            }
            Page<Order> pp = new Page<>(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
            returnPageModelJson(pp);
            return;
        }
        returnPageModelJson(page);
    }

    @ValidateForm
    public void getDetail() throws Exception {
        String openId = getSessionAttr("openId"); // "oULNBwOvt_D2A_8se1bQOQ06ky0w"; //
        Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number = ?", getPara("orderNumber"));
        if (openId != null && order != null && order.getStatusId() == 4) {
            if (order != null) {
                Map<String, Object> listDate = new HashMap<String, Object>();
                Map<String, Object> orderMap = new HashMap<String, Object>();
                Map<String, Object> sellerMap = new HashMap<String, Object>();
                Map<String, Object> spotMap = new HashMap<String, Object>();
                Map<String, Object> commodityMap = new HashMap<String, Object>();
                orderMap.put("nubmer", order.getOrderNumber());
                orderMap.put("amount", order.getAmount());
                orderMap.put("price", order.getUnitPrice());
                orderMap.put("amountPrice", order.getUnitPrice() * order.getAmount());
                orderMap.put("remark", order.getRemark());
                orderMap.put("payDate", order.getPaymentTime());

                Seller seller = Seller.dao.findById(order.getSellerId());
                if (seller != null) {
                    sellerMap.put("name", seller.getSellerName());
                    sellerMap.put("email", seller.getEmail());
                    sellerMap.put("phone", seller.getMobileNumber());
                    sellerMap.put("yuyue", seller.getYuyue() == 0 ? "无需预约" : "需要预约");
                }

                Ticket ticket = Ticket.dao.findById(order.getTargetId());
                if (ticket != null) {
                    commodityMap.put("name", ticket.getTitle());
                    commodityMap.put("verifyCode", AseUtils.aesDecrypt(order.getVerifyCode(), Constant.XinXiLan.ORDER_AES_KEY));
                    commodityMap.put("endDate", DateUtil.addDate(order.getPaymentTime(), 30));
                    orderMap.put("discount", ticket.getNzdPrice() / ticket.getOldNzdPrice());
                    orderMap.put("nzdPrice", ticket.getNzdPrice());
                }

                ScenicSpot spot = ScenicSpot.dao.findById(ticket.getScenicSpotId());
                if (spot != null) {
                    spotMap.put("name", spot.getScenicName());
                    spotMap.put("address", spot.getPosition());
                }

                listDate.put("commodity", commodityMap);
                listDate.put("order", orderMap);
                listDate.put("seller", sellerMap);
                listDate.put("spot", spotMap);
                renderJson(listDate);
            } else {
                returnFailureJson();
            }
        } else {

        }
    }

    public void getOperationOrder() {
        List<Order> list = Order.dao.find("SELECT * FROM `order` WHERE status_id=4 AND handle_time IS NULL ORDER BY create_time desc");
        List<Object> result = new ArrayList<Object>();
        for (Order order : list) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", order.getId());
            map.put("orderNumber", order.getOrderNumber());
            map.put("createTime", order.getCreateTime());
            result.add(map);
        }
        renderJson(result);
    }

    public void updateOrder() {
        String orderId = getPara("orderId");
        Order order = Order.dao.findById(orderId);
        Integer adminId = getSessionAttr("adminId");
        if (order != null && adminId != null) {
            order.setHandleTime(new Date());
            if (order.update()) {
                OperationHistory operationHistory = new OperationHistory();
                operationHistory.setAdminId(adminId);
                operationHistory.setTableName("order");
                operationHistory.setTargetId(order.getId());
                operationHistory.setTypeId(2L);
                operationHistory.setCreateTime(new Date());
                operationHistory.save();
                returnSuccessJson();
            }else{
                returnFailureJson();
            }
        } else {
            returnFailureJson();
        }
    }
}
